package websocket.stomp.endpoint;

import java.util.List;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import websocket.stomp.dto.NotifyDTO;
import websocket.stomp.dto.R;

@RestController
@RequestMapping("/websocket")
@AllArgsConstructor
public class WebSocketController {

    private SimpMessagingTemplate messagingTemplate;

    /**
     * 测试：推送消息给所有在线的人
     * 消息业务编码<br/>
     *            00-告警 <br/>
     *            01-系统公告<br/>
     *            11-请假审批列表刷新<br/>
     *            12-xxx列表状态变更刷新<br/>
     * @param notifyDTO：消息内容，JSONObject字符串
     */
    @PostMapping("/testSendAllMsg")
    public R testSendAllMsg(@RequestBody NotifyDTO notifyDTO) {
        messagingTemplate.convertAndSend("/topic/notice", this.messageResponse(notifyDTO));
        return R.ok();
    }

    /**
     * 测试：推送消息给单个人
     *
     * @param notifyDTO
     */
    @PostMapping("/testSendOneMsg")
    public void testSendOneMsg(@RequestBody NotifyDTO notifyDTO) {
        String userId = notifyDTO.getToUserIds().get(0) + "";
        messagingTemplate.convertAndSendToUser(userId + "", "/queue/chat", this.messageResponse(notifyDTO));
    }

    /**
     * 测试：推送消息给某些指定的人
     *
     * @param notifyDTO
     */
    @PostMapping("/testSendSomeMsg")
    public void testSendSomeMsg(@RequestBody NotifyDTO notifyDTO) {
        List<Integer> userIds = notifyDTO.getToUserIds();
        userIds.forEach(userId -> {
            messagingTemplate.convertAndSendToUser(userId + "", "/queue/chat", this.messageResponse(notifyDTO));
        });
    }

    /**
     * 封装推送消息
     *
     * @param notifyDTO
     * @return
     */
    private String messageResponse(NotifyDTO notifyDTO) {
        JSONObject jsonObject = JSONUtil.parseObj(notifyDTO);
        jsonObject.remove("toUserIds");
        return jsonObject.toString();
    }

    @MessageMapping("/hello")
    @SendToUser("/queue/chat")
    public String greeting(String message) {
        return "hello+5006端口";
    }

    /**
     * 推送消息给单个人
     *
     */
    @PostMapping("/sendNoticeInfo")
    public void sendNoticeInfo(@RequestBody NotifyDTO notifyDTO) {
        List<Integer> userIds = notifyDTO.getToUserIds();
        userIds.forEach(userId -> {
            messagingTemplate.convertAndSendToUser(userId + "", "/queue/chat", this.messageResponse(notifyDTO));
        });
    }
}
